package com.lill.auth2.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lill.auth2.constant.AuthConstant;
import com.lill.common.component.util.AESUtil;

public class OnceToken {

	private final static Logger log = LoggerFactory.getLogger(OnceToken.class);
	
	public static String createToken(String userId) {
		String contentToken="";
		try {
			Map<String, Object> headerClaims=new HashMap<String, Object>();
			headerClaims.put("time",new Date().getTime());
			headerClaims.put("company",AuthConstant.companyName);
			Algorithm algorithm=Algorithm.HMAC512(AESUtil.secretKey);
			String token=JWT.create().withHeader(headerClaims).withClaim("userId", userId).withIssuer(AuthConstant.issuer).sign(algorithm);
			contentToken=AESUtil.encrypt16(token);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return contentToken;
	}
	
	public static String createTokenWithUniqueCode(String userId,String uniqueCode) {
		String contentToken="";
		try {
			Map<String, Object> headerClaims=new HashMap<String, Object>();
			headerClaims.put("time",new Date().getTime());
			headerClaims.put("uniqueCode",uniqueCode);
			Algorithm algorithm=Algorithm.HMAC512(AESUtil.secretKey);
			String token=JWT.create().withHeader(headerClaims).withClaim("userId", userId).withIssuer(AuthConstant.issuer).sign(algorithm);
//			contentToken=AESUtil.encrypt16(token);
			contentToken=token;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return contentToken;
	}
	
	public static String decryptToken(String token) {
		String userId="";
		try {
			Algorithm algorithm=Algorithm.HMAC512(AESUtil.secretKey);
			JWTVerifier verifier=JWT.require(algorithm).build();
//			DecodedJWT jwt=verifier.verify(AESUtil.decrypt16(token));
			DecodedJWT jwt=verifier.verify(token);
			Map<String, Claim> mapClaim=jwt.getClaims();
			userId=mapClaim.get("userId").asString();
		} catch (Exception e) {
			userId=null;
			log.error("token:"+token+"**e:"+e.getMessage(), e);
		}
		return userId;
	}

}
